package cn.edu.gznu.wecampus.assistant.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.edu.gznu.wecampus.core.weixin.service.message.ITextMessageService;
import cn.edu.gznu.wecampus.core.weixin.service.message.MessageException;
import cn.edu.gznu.wecampus.core.weixin.service.message.Request;
import cn.edu.gznu.wecampus.core.weixin.service.message.Response;
import cn.edu.gznu.wisedu.entity.ldap.Member;
import cn.edu.gznu.wisedu.repository.ldap.MD4;
import cn.edu.gznu.wisedu.repository.ldap.MemberRepository;

@Service
public class ResetPasswordMessageService implements ITextMessageService {
	
	@Autowired
	private MemberRepository memberRepository;

	@Override
	public Response process(Request request) {
		String[] splits = splits(request.getContent());
		String xgh = request.getFromUserName();
		String sfzjh = splits[1];
		Member member = memberRepository.findByXgh(xgh);
		if(member == null) {
			throw new MessageException("学工号不匹配");
		}
		if(!StringUtils.equals(member.getEduPersonCardID().substring(12), sfzjh)) {
			throw new MessageException("身份证号验证不通过");
		}
		member.setOtherPassword(MD4.getMD4(sfzjh));
		member.setUserPassword(sfzjh);
		memberRepository.save(member);
        Response response = new Response();
        response.setToUserName(request.getFromUserName());
        response.setFromUserName(request.getToUserName());
        response.setCreateTime(request.getCreateTime());
        response.setMsgType("text");
        response.setContent("您的统一身份认证密码已重置为身份证后六位，请尽快修改并妥善保管！");
        return response;
	}

	@Override
	public boolean checkContent(Request request) {
		String[] splits = this.splits(request.getContent());
		if(!StringUtils.equals(splits[0], "重置密码")) {
			return false;
		}
		return true;
	}
	
	private String[] splits(String content) {
		String serviceName = StringUtils.substring(content, 0, 4);
		String sfzjh = StringUtils.substring(content, 4).trim();
		return new String[] {serviceName, sfzjh};
	}
}
